﻿#region License
/* Copyright (C) 2009 Tim Coulter
 * 
 * This file is part of ExtremeML.
 * 
 * ExtremeML is free software: you can redistribute
 * it and/or modify it under the terms of the GNU General Public
 * License, as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 * 
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
 * the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
*/
#endregion

using System;
using System.Drawing;
using System.Windows.Forms;
using ExtremeML.Core;

namespace ExtremeML.Spreadsheet
{
	// This is a partial class that adds custom functionality to its auto-generated partner.
	public sealed partial class FontWrapper
	{
		#region Custom Properties

		private int? _maximumDigitWidth;

		/// <summary>
		/// Gets the Maximum Digit Width (in pixels) for the associated font.
		/// </summary>
		internal int MaximumDigitWidth
		{
			get
			{
				if (!_maximumDigitWidth.HasValue)
				{
					_maximumDigitWidth = GetMaximumDigitWidth();
				}

				return _maximumDigitWidth.Value;
			}
		}

		#endregion
		#region Custom Methods


		#endregion
		#region Overrides


		#endregion
		#region Implementation Methods

		/// <summary>
		/// Returns the Maximum Digit Width (in pixels) for the associated font, as determined using the recognised technique.
		/// (See http://stackoverflow.com/questions/1833062/how-to-measure-the-pixel-width-of-a-digit-in-a-given-font-size-c)
		/// </summary>
		/// <returns>An <see cref="int"/> that represents the pixel width of the widest digit.</returns>
		private int GetMaximumDigitWidth()
		{
			if (FontName.Val != null && FontSize.Val.HasValue)
			{
				var font = new Font(FontName.Val, (float)FontSize.Val.Value, GraphicsUnit.Point);
				var width = 0;

				for (var i = 0; i < 10; i++)
				{
					var oneDigit = TextRenderer.MeasureText(i.ToString(), font).Width;
					var twoDigits = TextRenderer.MeasureText(new string(i.ToString()[0], 2), font).Width;
					width = Math.Max(width, twoDigits - oneDigit);
				}

				return width;
			}

			throw new PackageException("Underlying package element definition is incomplete.");
		}

		#endregion
		#region Static Methods


		#endregion
	}
}
